package com.yq.reggie.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 上传与下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    /**
     * 图片上传
     * @param file
     * @return
     */
    @Value("${common.path}")
    private String path;

    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        log.info("图片上传：{}",file);
        //重新定义图片名称
        String name = file.getOriginalFilename();
        String suffix = name.substring(name.indexOf("."));
        name = UUID.randomUUID() + suffix;
        //判断当前目录是否存在,不存在则创建
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //将图片转存
        try {
            file.transferTo(new File(path+name));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.success(name);
    }

    /**
     * 下载图片
     * @return
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream inputStream= new FileInputStream(new File(path + name));
            //输出流，通过输出流将文件写回浏览器，在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len=0;
            byte[] bytes =new byte[1024];
            while((len=inputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //清理资源
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
